package com.laboratory.servicecustomer.util;

import com.laboratory.servicecustomer.constant.constantArgs;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @Author acok
 * @description: 文件辅助类
 * @Date 2022/12/27 8:26
 * @Version 1.0
 */
public class fileUtil {
  /**
       * @return: 文件处理结果
       * @param: 文件实体
       * @description: 将前端传递文件保存至本地指定文件库
       * @Author: Acok
       * @mbggenerated 2023/4/25
       */
    public static String SaveFileToLocal(MultipartFile file){
        String fileName=UUID.randomUUID().toString();
        String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (file.isEmpty()) {
            return "false";
        }
        /*String fileName = file.getOriginalFilename();*/
        String path=new File(constantArgs.LOCAL_SERVICE_FILE_FOLDER).getAbsolutePath()+ "/" + fileName+fileSuffix;
        File dest = new File(path);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
    /**
     * @return: null
     * @param: 待关闭流
     * @description: 关闭文件流
     * @Author: Acok
     * @mbggenerated 2023/1/6
     */
    public static void closeFileStream(OutputStream outWeb, HSSFWorkbook wb){
        if(wb!=null){
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(outWeb!=null){
            try {
                outWeb.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
